package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.gulimall.search.config.ElasticConfig;
import com.atguigu.gulimall.search.constant.EsConstant;
import com.atguigu.gulimall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {
    @Autowired
    private RestHighLevelClient esClient;

    @Override
    public Boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        // 保存到es
        // 1、 给es建立索引 product,建立映射关系
        // 使用bulk 批量操作保存所有sku数据

        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            // 设置ID
            indexRequest.id(skuEsModel.getSkuId().toString());
            // 设置数据内容，数据格式
            indexRequest.source(JSON.toJSONString(skuEsModel), XContentType.JSON);
            // 批量添加
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulkResponse = esClient.bulk(bulkRequest, ElasticConfig.COMMON_OPTIONS);
        // 处理返回结果
        boolean hasFailures = bulkResponse.hasFailures();
        if (hasFailures) {
            // todo 处理错误
            List<String> errCollect = Arrays
                    .stream(bulkResponse.getItems())
                    .map(item -> {
                        return item.getId();
                    })
                    .collect(Collectors.toList());
            log.error("商品商家错误：{}", errCollect);
        }
        return !hasFailures;
    }
}
